$(function(){
	var defaults = {
			view:{
				showSearchToolbar:false,/**是否显示查询工具栏*/
				showButtonToolbar:false,/**是否显示操作按钮工具栏*/
				searchToolbar:[],
				buttons:[]
			},
			data:{
				singleSelect:false,
				pagination:true,
				firstLoad:true,
				queryParams:{},
				url:null,
				params:{},
				columns:[],
				onSelect:function(rowIndex, rowData){}
			}
	};
	var datagrid_table = null;
	$.fn.pageView = function (options,params) {
		if(typeof options=="string"){
			return $.fn.pageView.methods[options](this,params);
		}
		var options_view =$.extend(defaults.view, options.view);
		var options_data =$.extend(defaults.data, options.data);
		options={
				view:options_view,
				data:options_data,
		}
		var _view = this;
		$(_view).data("options",options);
		var showSearchToolbar = options.view.showSearchToolbar;
		var showButtonToolbar = options.view.showButtonToolbar;
		var page_uuid = uuid();
		
		var table_id = "datagrid_"+page_uuid;
		datagrid_table = $(' <table class="datagrid" id="'+table_id+'"></table>');
		$(_view).append($(datagrid_table));
		
		var tool_bar_id = "tool_bar_"+page_uuid;
		var tool_bar = $('<div id="'+tool_bar_id+'" style="padding: 5px; height: auto"></div>');
		$(_view).append($(tool_bar));
		var tool_bar_div = $("<div></div>");
		$(tool_bar).append($(tool_bar_div));
		if(showSearchToolbar){
			var search_tool_bar_form = $('<div style="display:block;position: absolute;right: 50px;top: 5px;" id="search_from_'+page_uuid+'" action=""></div>');
			$(tool_bar_div).append($(search_tool_bar_form));
			var searchToolbar = options.view.searchToolbar;
			if(searchToolbar){
				for(var a0=0;a0<searchToolbar.length;a0++){
					var searchBar0 = searchToolbar[a0];
					if(searchBar0.type="text"){
						var search_tool_bar_input = $('<input type="text" style="margin-right:4px;" name="'+searchBar0.name+'"/>');
						$(search_tool_bar_form).append($(search_tool_bar_input));
						$(search_tool_bar_input).validatebox({
							width:searchBar0.width||150,prompt:searchBar0.label
						});
					}
				}
			}
			
			var search_tool_bar_btn = $('<a href="javascript(0)" style="position: absolute;right: 0px;top: 3px;">查询</a>');
			$(tool_bar).append($(search_tool_bar_btn));
			$(search_tool_bar_btn).linkbutton({
				iconCls:"icon-search",
				plain:true
			});
			$(search_tool_bar_btn).bind('click', function(){
				var obj = $('#search_from_'+page_uuid).serializeObject();
				$(datagrid_table).datagrid('load', obj);
		    });
		}
		if(showButtonToolbar){
			var buttons = options.view.buttons;
			if(buttons){
				for(var a0=0;a0<buttons.length;a0++){
					var button = buttons[a0];
					var button_01 = $('<a href="javascript:void(0)"></a>');
					$(tool_bar_div).append($(button_01));
					$(button_01).linkbutton({
						iconCls:button.iconCls,
						text:button.label,
						plain:true,
					});
					$(button_01).data(button);
					
					if(button.type=="button"){
						
						$(button_01).bind("click",function(){
							if(options.data.singleSelect){
								var selected = _view.getSelections();
								if(selected&&selected.length>0){
									$(this).data().click(_view,selected[0]);
								}else{
									$(this).data().click(_view,null);
								}
							}else{
								var selected = _view.getSelections();
								$(this).data().click(_view,selected);
							}
		 				});
					}else if(button.type=="tabs"){
						$(button_01).bind("click",function(){
							var that_btn = this;
							var href = $(that_btn).data("href");
							var queryParams = _view.getQueryParams();
							if(null!=queryParams){
								var paramStr = CommonUtil.parseParam(queryParams);
								if(href.indexOf("?")>0){
									href=href+"&"+paramStr;
								}else{
									href=href+"?"+paramStr;
								}
							}
							if($(that_btn).data("key")){
								var selected = null;
								if(_view.getSelections().length>0){
									selected = _view.getSelections()[0];
									if(href.indexOf("?")>0){
										href=href+"&"+$(that_btn).data("key")+"="+selected[$(that_btn).data("key")];
									}else{
										href=href+"?"+$(that_btn).data("key")+"="+selected[$(that_btn).data("key")];
									}
								}else{
									return false;
								}
							}
							parent.window.mainpage.mainTabs.addModule($(that_btn).data("label"),href,$(that_btn).data("iconCls"));
							
		 				});
					}else if(button.type=="delete"){
						$(button_01).bind("click",function(){
							var that_btn = this;
							if(options.data.singleSelect){
								var selected = _view.getSelections();
								if(selected&&selected.length>0){
									parent.$.messager.confirm('提示', '确认要删除？', function(confirm){
										if(confirm){
											$.post($(that_btn).data("src"),selected[0],function(data){
												_view.reload();
												parent.$.messager.show({ title : "提示",msg: "删除成功", position: "bottomRight" });
											});
										}
									});
								}
							}else{
								//var selected = _view.getSelections();
								//$(this).data().click(_view,selected);
							}
		 				});
					}else if(button.type=="edit"){
						$(button_01).bind("click",function(){
							var that_btn = this;
							var selected = null;
							if(_view.getSelections().length>0){
								selected = _view.getSelections()[0];
								parent.$.WindowView({
									title:$(that_btn).data("label"),
									href:$(that_btn).data("href"),
									action:$(that_btn).data("action"),
									width:$(that_btn).data("width"),
									height:$(that_btn).data("height"),
									formData:selected,
									key:$(that_btn).data("key"),
									view:_view,
									buttonShow:true
								});
							}
		 				});
					}else if(button.type=="add"){
						$(button_01).bind("click",function(){
							var that_btn = this;
							var href = $(that_btn).data("href");
							debugger;
							var queryParams = _view.getQueryParams();
							if(null!=queryParams){
								var paramStr = CommonUtil.parseParam(queryParams);
								if(href.indexOf("?")>0){
									href=href+"&"+paramStr;
								}else{
									href=href+"?"+paramStr;
								}
							}
							parent.$.WindowView({
								title:$(that_btn).data("label"),
								href:href,
								action:$(that_btn).data("action"),
								width:$(that_btn).data("width"),
								height:$(that_btn).data("height"),
								formData:$(that_btn).data("paramFlag")?qps:{},
								view:_view,
								buttonShow:true
							});
		 				});
					}
				}
			}
		}
		//console.info(options.data.onSelect);
		$(datagrid_table).datagrid({
			method : "POST",
			fit : true,
			fitColumns : true,
			border : false,
			idField : 'id',
			striped : true,
			pagination :options.data.pagination,
			rownumbers : true,
			pageNumber : 1,
			pageSize : 20,
			pageList : [ 10, 20, 30, 40, 50 ],
			singleSelect : options.data.singleSelect,
			columns : options.data.columns,
			headerContextMenu : [{
				text : "冻结该列",
				disabled : function(e, field) {
					return $(datagrid_table).datagrid("getColumnFields",
							true).contains(field);
				},
				handler : function(e, field) {
					$(datagrid_table).datagrid("freezeColumn", field);
				}
			},
			{
				text : "取消冻结该列",
				disabled : function(e, field) {
					return $(datagrid_table).datagrid("getColumnFields",false).contains(field);
				},
				handler : function(e, field) {$(datagrid_table).datagrid("unfreezeColumn", field);}
			}],
			enableHeaderClickMenu : true,
			enableHeaderContextMenu : true,
			enableRowContextMenu : false,
			toolbar:"#"+tool_bar_id,
			onSelect:options.data.onSelect||null
		});
		if(options.data.firstLoad){
			$(datagrid_table).datagrid('options').url=options.data.url;
			$(datagrid_table).datagrid('reload');
		}
		
		_view.getSelections=function(){
			return $(this).find("table.datagrid").datagrid("getSelections");
		}
		_view.getQueryParams=function(){
			return $(this).find("table.datagrid").datagrid("options").queryParams;
		}
		_view.reload=function(){
			var queryParams = $(this).find("table.datagrid").datagrid('options').queryParams;
			$(this).find("table.datagrid").datagrid('reload',queryParams);
			$(this).find("table.datagrid").datagrid("clearSelections");
		}
		return _view;
	}
	$.fn.pageView.methods = {
		options:function(jq){
			return $(jq[0]).data("options");
		},
		queryParams:function(jq){
			return $(jq[0]).data("options").data.queryParams;
		},
		reload:function(jq,params){
			if(params){
				if(params.url){
					$(jq[0]).find("table.datagrid").datagrid('options').url=params.url;
				}
				if(params.queryParams){
					$(jq[0]).find("table.datagrid").datagrid('reload',params.queryParams);
				}else{
					var queryParams = $(jq[0]).find("table.datagrid").datagrid('options').queryParams;
					$(jq[0]).find("table.datagrid").datagrid('reload',queryParams);
				}
			}else{
				var queryParams = $(jq[0]).find("table.datagrid").datagrid('options').queryParams;
				$(jq[0]).find("table.datagrid").datagrid('reload',queryParams);
			}
			
			
		}
	};
	function uuid() {
	    var s = [];
	    var hexDigits = "0123456789abcdef";
	    for (var i = 0; i < 36; i++) {
	        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	    }
	    s[14] = "4";
	    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
	    s[8] = s[13] = s[18] = s[23] = "-"; 
	    var uuid = s.join("");
	    return uuid;
	}
	Date.prototype.format = function(fmt){
		var o = {
			"M+": this.getMonth() + 1, //月份
			"D+": this.getDate(), //日
			"d+": this.getDate(), //日
			"H+": this.getHours(), //小时
			"h+": this.getHours(), //小时
			"m+": this.getMinutes(), //分
			"s+": this.getSeconds(), //秒
			"q+": Math.floor((this.getMonth() + 3) / 3), //季度
			"S": this.getMilliseconds() //毫秒
		};
		if (/([Y,y]+)/.test(fmt)){
			fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
		}
		for (var k in o){
			if(new RegExp("(" + k + ")").test(fmt)){
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
			}
		}
		return fmt;
	};
});